#!/bin/sh

die () { echo "$@" ; exit 1; }

\. ../../../nvm.sh

set -e

ESC="$(printf '\033')"
# The legend's letters are wrapped in color codes when the terminal supports
# them, so every text assertion below compares against the output with any
# escapes removed. That keeps these checks about structure and alignment only.
strip_colors() { command sed "s/${ESC}\[[0-9;]*m//g"; }

command -v nvm_print_color_legend >/dev/null 2>&1 \
  || die 'nvm_print_color_legend is not defined'

OUTPUT="$(nvm_print_color_legend)"

LINES="$(nvm_echo "${OUTPUT}" | command wc -l | command tr -d ' ')"
[ "${LINES}" = 11 ] || die "expected 11 legend lines, got ${LINES}: ${OUTPUT}"

PLAIN="$(nvm_echo "${OUTPUT}" | strip_colors)"

# the two labels are literal, and their indentation lines the legend up under
# the `nvm set-colors` entry in the help output
nvm_echo "${PLAIN}" | nvm_grep -qx '                                               Initial colors are:' \
  || die "the 'Initial colors are:' label is missing or misaligned: ${PLAIN}"
nvm_echo "${PLAIN}" | nvm_grep -qx '                                               Color codes:' \
  || die "the 'Color codes:' label is missing or misaligned: ${PLAIN}"

# the default-palette sample, indented one level deeper than its label
nvm_echo "${PLAIN}" | nvm_grep -qx '                                                  bygre' \
  || die "the initial-colors sample is missing or misaligned: ${PLAIN}"

# all eight rows of the code table, in order, each with both letter forms
for ROW in \
  'r/R = red / bold red' \
  'g/G = green / bold green' \
  'b/B = blue / bold blue' \
  'c/C = cyan / bold cyan' \
  'm/M = magenta / bold magenta' \
  'y/Y = yellow / bold yellow' \
  'k/K = black / bold black' \
  'e/W = light grey / white' \
; do
  nvm_echo "${PLAIN}" | nvm_grep -qx "                                                ${ROW}" \
    || die "color code row '${ROW}' is missing or misaligned: ${PLAIN}"
done

# the extracted function has to stay wired into the help output
nvm --help | strip_colors | nvm_grep -qx '                                               Color codes:' \
  || die 'nvm --help no longer includes the color legend'

# and `nvm unload` has to clean it up, the way it does its sibling helpers
UNLOADED="$( (nvm unload >/dev/null 2>&1; command -v nvm_print_color_legend >/dev/null 2>&1 && echo present || echo gone) )"
[ "${UNLOADED}" = 'gone' ] || die 'nvm unload left nvm_print_color_legend defined'

echo "nvm_print_color_legend: passed"
